from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
#By类，用于定位元素
from selenium.webdriver.common.by import By
#显示等待相关的类
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
service = Service("d:/chromedriver/chromedriver-win64/chromedriver.exe")
driver = webdriver.Chrome(service=service)
try:
    driver.get("https://www.baidu.com")
    search_box = driver.find_element(By.ID, "kw")
    search_box.send_keys("iphone16")
    #点击搜索按钮
    search_button = driver.find_element(By.ID, "su")
    search_button.click()
    #显示等待
    wait = WebDriverWait(driver, 10)
    search_results = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".result h3 a")))
    results = []  #空列表
    for result in  search_results:
        title = result.text
        link = result.get_attribute("href")
        results.append((title, link))
    #结果写入文件
    with open("baidu.txt", "w", encoding="utf-8") as  f:
        for title, link in results:
            f.write(f"Title:{title}\nLink:{link}\n\n")
except Exception as  e:
    print(f"发生了错误{e}")
finally:
    time.sleep(5)
    driver.quit()   #关浏览器和驱动